package com.caijb.juc;

import java.util.concurrent.Semaphore;

/**
 * @author caijb
 * @version 1.0
 * @data 2025/10/27 20:26
 */
public class SemaphoreDemo {
    public static void main(String[] args) throws InterruptedException {
        ParkingLot parkingLot = new ParkingLot(5);
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
                    parkingLot.park(finalI);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                try {
                    Thread.sleep(5 * 1000L);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                parkingLot.leave(finalI);
            }, "Thread-" + i).start();
        }
    }

    /**
     * 模拟一个停车场
     */
    static class ParkingLot {
        private Semaphore semaphore;
        private int capacity;


        /**
         * 创建停车场
         * @param capacity 停车场容量
         */
        public ParkingLot(int capacity) {
            this.capacity = capacity;
//            semaphore = new Semaphore(capacity);
            semaphore = new Semaphore(capacity, true);
        }
        /**
         * 停入
         * @throws InterruptedException
         */
        public void park(int i) throws InterruptedException {
            long start = System.currentTimeMillis();
            semaphore.acquire();
            System.out.println("车辆"+i+"Parking...,等待时间："+(System.currentTimeMillis()-start)+"ms");
        }
        /**
         * 停出
         */
        public void leave(int i) {
            semaphore.release();
            System.out.println("车辆"+i+"Leaving...");
        }
        /**
         * 获取剩余车位数
         * @return
         */
        public int getAvailableSpots() {
            return semaphore.availablePermits();
        }
        /**
         * 获取停车场容量
         * @return
         */
        public int getCapacity() {
            return capacity;
        }
    }
}
